<template>
  <!-- 添加或修改客户报修抢修对话框 -->
  <el-dialog title="商家基本信息" :visible.sync="open" width="960px" append-to-body>
    <el-form
      ref="serviceRef"
      :model="form"
      :rules="rules"
      label-width="140px"
    >
      <el-row>
        <el-col :span="16">
          <el-form-item label="地区" prop="region">
            <v-distpicker @province="onChangeProvince" @city="onChangeCity" @area="onChangeArea" province="云南省" :city="form.city" :area="form.area" placeholder="请选择地区"></v-distpicker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="默认接单">
            <el-radio-group v-model="form.receiver">
              <el-radio
                v-for="dict in dict.type.yes_or_no"
                :key="Number(dict.value)"
                :label="Number(dict.value)"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="服务类型" prop="serviceType">
            <el-cascader
              style="width:100%"
              :options="serviceType"
              :props="{ multiple: true, emitPath: false }"
              v-model="form.serviceType"
              clearable
            >
            </el-cascader>
<!--            <el-select style="width:100%" multiple v-model="form.serviceType" placeholder="请选择服务类型">
              <el-option label="客户报修抢修" value="客户报修抢修"></el-option>
              <el-option label="线路委托运维" value="线路委托运维"></el-option>
              <el-option label="充电桩运维" value="充电桩运维"></el-option>
              <el-option label="配电室运维" value="配电室运维"></el-option>
              <el-option label="电子化移交" value="电子化移交"></el-option>
              <el-option label="高低压业扩" value="高低压业扩"></el-option>
              <el-option label="带电作业服务" value="带电作业服务"></el-option>
              <el-option label="电气设备预试" value="电气设备预试"></el-option>
              <el-option label="配电设备销售" value="配电设备销售"></el-option>
              <el-option label="临电共享服务" value="临电共享服务"></el-option>
            </el-select>-->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="归属部门" prop="parentId">
            <treeselect v-model="form.parentId" :options="deptList" :normalizer="normalizer" placeholder="请选择归属部门" />
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="商家名称" prop="deptName">
            <el-input v-model.trim="form.deptName" placeholder="请输入商家名称" />
          </el-form-item>

        </el-col>
      </el-row>
      <el-row v-if="form.deptInfo">

        <el-col :span="10">
          <el-form-item label="统一社会信用代码">
            <el-input v-model="form.deptInfo.creditCode" placeholder="请输入统一社会信用代码" />
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="法人">
            <el-input v-model="form.deptInfo.legalPerson" placeholder="请输入法人" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.deptInfo">
        <el-col :span="10">
          <el-form-item label="法人电话">
            <el-input v-model="form.deptInfo.legalPhone" placeholder="请输入法人电话" />
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="法人身份证号">
            <el-input v-model="form.deptInfo.legalCode" placeholder="请输入法人身份证号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.deptInfo">
        <el-col :span="10">
          <el-row>
            <el-col :span="24">
              <el-form-item label="联系人">
                <el-input v-model="form.deptInfo.contact" placeholder="请输入联系人" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="联系人电话">
                <el-input v-model="form.deptInfo.contactPhone" placeholder="请输入联系人电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="注册日期">
                <el-date-picker
                  style="width:100%"
                  v-model="form.deptInfo.registerDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择注册日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="经纬度" prop="lngAndLat">
              <el-input
                v-model="form.lngAndLat"
                placeholder="请输入经纬度"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="注册地址" prop="address">
                <el-input
                  v-model="form.address"
                  type="textarea"
                  placeholder="请输入注册地址"
                  @blur="getNewLocation"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="14">
          <el-form-item label="搜索位置">
            <baidu-map
              :scroll-wheel-zoom="true"
              style="width:100%;height:300px;display:flex;flex-direction: column-reverse;"
              :center="center"
              :zoom="zoom"
              @click="getLocation"
              @ready="handler">
              <bm-view style="width: 100%; height: 300px"></bm-view>
              <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
              <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
              <div style="display:flex;margin-bottom: 15px">
                <bm-auto-complete :sugStyle="{zIndex: 999999}">
                  <el-input v-model="searchAddress" style="width:310px;margin-right:15px" placeholder="搜索地址"></el-input>
                </bm-auto-complete>
                <el-button type="primary" @click="getBaiduMapPoint">搜索</el-button>
              </div>
              <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type>
              <bm-marker v-if="infoWindowShow" :position="{lng: longitude, lat: latitude}">
                <bm-label content="" :labelStyle="{color: 'red', fontSize : '24px'}" :offset="{width: -35, height: 30}"/>
              </bm-marker>
            </baidu-map>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.deptInfo">
        <el-col :span="12">
          <el-form-item label="营业执照">
            <file-upload :fileSize="10" :fileType="['png', 'jpg', 'jpeg', 'pdf']" v-model="form.deptInfo.businessLicense" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司资质">
            <file-upload :fileSize="10" :fileType="['png', 'jpg', 'jpeg', 'pdf']" v-model="form.deptInfo.companyQualification" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="身份证复印件" v-if="form.deptInfo">
        <file-upload :fileSize="10" :fileType="['png', 'jpg', 'jpeg', 'pdf']" v-model="form.deptInfo.customerFiles" />
      </el-form-item>

      <el-descriptions title="收款信息"></el-descriptions>
      <el-row>
        <el-col :span="12">
          <el-form-item label="分账收款方式" prop="checkType">
            <el-select style="width:100%" v-model="form.checkType" placeholder="请选择公司分账收款方式">
              <el-option label="公司钱包" :value="0"></el-option>
<!--              <el-option label="微信" :value="1"></el-option>-->
              <el-option label="支付宝" :value="2"></el-option>
              <el-option label="银行卡" :value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="师傅分账比例" prop="workerRatio">
            <el-input-number v-model="form.workerRatio" :step="0.1" :min="0" :max="1" placeholder="0.1代表10%"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.deptInfo">
        <el-col :span="12">
          <el-form-item label="支付宝账号" prop="zhiFuBao">
            <el-input v-model.trim="form.deptInfo.zhiFuBao" placeholder="请输入收款支付宝账号" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付宝名称" prop="zhiFuBaoName">
            <el-input v-model="form.deptInfo.zhiFuBaoName" placeholder="请输入收款支付宝名称" maxlength="50" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.deptInfo">
        <el-col :span="12">
          <el-form-item label="银行卡号" prop="payBankCard">
            <el-input v-model.trim="form.deptInfo.payBankCard" placeholder="请输入银行卡号" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户行" prop="payBankName">
            <el-input v-model="form.deptInfo.payBankName" placeholder="请输入开户行" maxlength="50" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.deptInfo">
        <el-col :span="12">
          <el-form-item label="姓名" prop="payBankUser">
            <el-input v-model="form.deptInfo.payBankUser" placeholder="请输入姓名" maxlength="50" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.deptInfo">
        <el-col :span="23">
          <el-form-item label="微信收款码">
            <file-upload :fileType="['png', 'jpg', 'jpeg', 'pdf']" v-model="form.deptInfo.payWeixin" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.deptInfo">
        <el-col :span="23">
          <el-form-item label="支付宝收款码">
            <file-upload :fileType="['png', 'jpg', 'jpeg', 'pdf']" v-model="form.deptInfo.payApily" />
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
        >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import VDistpicker from 'v-distpicker'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { addDept, delDept, getDept, listDept, listDeptExcludeChild, updateDept } from '@/api/system/dept'

import { handleTree } from '@/utils/ruoyi'
import { ba_gd, gcj02tobd09 } from '@/utils/index'
import { allServeClassify, allTreeServeClassify } from '@/api/web/ServeClassify'

export default {
  name: "Dispatch",
  dicts: ['yes_or_no'],
  components: {Treeselect, VDistpicker },
  data() {
    return {
      searchAddress:'',
      infoWindowShow:false,
      longitude:'',
      latitude:'',
      center: {lng: 98.581008, lat: 24.442485}, // 定位位置116.413384, 39.910925
      zoom: 17, // 地图放大等级
      deptOptions: [], // 部门树选项
      deptName: undefined,   // 部门名称
      defaultProps: {
        children: "children",
        label: "deptName"
      },
      order: {},
      dialogVisible: false,
      btnLoading: false,
      serviceList: [],
      open: false,
      buttonLoading: false,
      loading: true,
      showSearch: true,
      ids: [],
      form: {
        deptInfo: {},
        province: '云南省',
        city: '德宏傣族景颇族自治州',
        area: ''
      },
      queryParams: {
        typeId: 3
      },
      serviceType: [],
      rules: {
        province: [
          { required: true, message: "所属省份不能为空", trigger: "change" },
        ],
        city: [
          { required: true, message: "所属城市不能为空", trigger: "change" },
        ],
        parentId: [
          { required: true, message: "归属部门不能为空", trigger: "change" },
        ],
        deptName: [
          { required: true, message: "商家名称不能为空", trigger: "blur" },
        ],
        address: [
          { required: true, message: "注册地址不能为空", trigger: "blur" },
        ],
        // lngAndLat: [{ required: true, message: "经纬度不能为空", trigger: "blur" }],
        serviceType: [{ required: true, message: "服务类型不能为空", trigger: "blur" }],
      },
      deptList: []
    }
  },
  created() {
    this.form.province = '云南省'
    this.form.city = '德宏傣族景颇族自治州'
    this.queryServiceType()
  },
  watch: {
    open(newValue) {
      listDept({typeId: 3}).then(response => {
        const parent = [{
          deptId: 100,
          ancestors: 0,
          parentId: 0,
          deptName:"易用能管理平台"
        }]
        this.deptList = handleTree(parent.concat(response.data), "deptId");
        // console.log(this.deptOptions)
      });
      // listDept(this.queryParams).then(response => {
      //   console.log(response)
      //   if (response.code == 200) {
      //     this.deptOptions = response.data
      //   }
      // });
    }
  },
  methods: {
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    queryServiceType() {
      allTreeServeClassify().then(res => {
        this.serviceType = res.data;
      })
    },
    changeService(value) {
      console.log(value)
      console.log(this.form.serviceType)
      // this.queryParams.serviceType = this.queryParams.serviceType.join(',')
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptInfo: {}
      };
      // this.resetForm("serviceRef");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      // this.form.deptInfo = {}

    },
    /** 修改按钮操作 */
    handleUpdate() {
      console.log(this.$parent.clickItem)
      const row = this.$parent.clickItem
      this.loading = true;
      this.reset();
      getDept(row.deptId).then(response => {
        this.form = response.data;
        if (!this.form.deptInfo) {
          this.form.deptInfo = {}
        }
        if (typeof response.data.serviceType == 'string') {
          this.form.serviceType = response.data.serviceType.split(',')
        }
        let temp = gcj02tobd09(response.data.lon, response.data.lat)
        this.form.lngAndLat = `${temp[1]},${temp[0]}`
        this.center = {lng: parseFloat(temp[0]), lat: parseFloat(temp[1])}
        this.infoWindowShow = true
        this.longitude = parseFloat(temp[0])
        this.latitude = parseFloat(temp[1])

        this.open = true;
        this.loading = false;
        listDeptExcludeChild(row.deptId).then(response => {
          this.deptList = handleTree(response.data.filter(r => r.typeId !== 4).filter(r => r.typeId !== 2), "deptId");
          if (this.serviceList.length == 0) {
            const noResultsOptions = { deptId: this.form.parentId, deptName: this.form.parentName, children: [] };
            this.deptList.push(noResultsOptions);
          }
        });
      });
    },

    onChangeProvince(a){
      console.log(a)
      this.form.province = a.value
      // this.txt1 = a.value + '-'
      // this.searchAddress = this.form.province + (this.form.city + '') + (this.form.area || '')
      // this.form.address = (this.form.province || '云南省') + (this.form.city + '') + (this.form.area || '')
      // this.getBaiduMapPoint()
    },
    onChangeCity(a){
      console.log(a)
      this.form.city = a.value
      // this.txt2 = a.value + '-'
      // this.searchAddress = this.form.province + (this.form.city + '') + (this.form.area || '')
      // this.form.address = (this.form.province || '云南省') + (this.form.city + '') + (this.form.area || '')
      // this.getBaiduMapPoint()
    },
    onChangeArea(a){
      console.log(a)
      this.form.area = a.value
      // this.txt3 = a.value
      this.show=false
      // this.searchAddress = this.form.province + (this.form.city + '') + (this.form.area || '')
      // this.form.address = (this.form.province || '云南省') + (this.form.city + '') + (this.form.area || '')
      // this.getBaiduMapPoint()
    },
    //点击地图获取经纬度
    getLocation(e){
      console.log(e)
      this.longitude=e.point.lng
      this.latitude=e.point.lat
      this.infoWindowShow=true
      // this.center = {lng: e.point.lng, lat: e.point.lat}
      this.form.lngAndLat = `${e.point.lng},${e.point.lat}`
      const myGeo = new BMap.Geocoder();
      this.point = new BMap.Point(e.point.lng,e.point.lat); // 116.413384, 39.910925
      const that = this
      myGeo.getLocation(this.point,function(result){
        console.log(result)
        // that.searchAddress = result.address
        // that.form.address = result.address; //获取到当前定位的详细地址信息
        if (result.surroundingPois && result.surroundingPois[0] && result.surroundingPois[0].point) {
          that.form.address = result.surroundingPois[0].address + result.surroundingPois[0].title;
          that.longitude=result.surroundingPois[0].point.lng
          that.latitude=result.surroundingPois[0].point.lat
          that.center = {lng: result.surroundingPois[0].point.lng, lat: result.surroundingPois[0].point.lat}
          that.form.lngAndLat = `${result.surroundingPois[0].point.lng},${result.surroundingPois[0].point.lat}`
        } else {
          that.form.address = result.address; //获取到当前定位的详细地址信息
          that.longitude=result.point.lng
          that.latitude=result.point.lat
          that.center = {lng: result.point.lng, lat: result.point.lat}
          that.form.lngAndLat = `${result.point.lng},${result.point.lat}`
        }
        // that.$set(that.form, 'address', result.address)
      });
    },
    getNewLocation() {
      let that=this
      let myGeo = new this.BMap.Geocoder()
      myGeo.getPoint(this.form.address,function(point){
        if(point){
          // that.map.centerAndZoom(point,15)
          that.latitude=point.lat
          that.longitude=point.lng
          that.infoWindowShow=true
          that.center = {lng: point.lng, lat: point.lat}
          that.form.lngAndLat = `${point.lng},${point.lat}`
        }

      })
    },
    // 搜索
    getBaiduMapPoint() {
      console.log(this.searchAddress)
      let that=this
      // that.form.address = this.searchAddress;
      let myGeo = new this.BMap.Geocoder()
      myGeo.getPoint(this.searchAddress,function(point){
        if(point){
          console.log(point, 'llll')
          // that.map.centerAndZoom(point,15)
          that.latitude=point.lat
          that.longitude=point.lng
          that.infoWindowShow=true
          that.center = {lng: point.lng, lat: point.lat}
          that.form.lngAndLat = `${point.lng},${point.lat}`
          if (point) {
            const myGeo = new BMap.Geocoder();
            that.point = new BMap.Point(point.lng,point.lat); // 116.413384, 39.910925
            myGeo.getLocation(that.point,function(result){
              console.log(result)
              // that.searchAddress = result.address
              // that.form.address = result.address; //获取到当前定位的详细地址信息
              if (result.surroundingPois && result.surroundingPois[0] && result.surroundingPois[0].point) {
                that.form.address = result.surroundingPois[0].address + result.surroundingPois[0].title;
                that.longitude=result.surroundingPois[0].point.lng
                that.latitude=result.surroundingPois[0].point.lat
                that.center = {lng: result.surroundingPois[0].point.lng, lat: result.surroundingPois[0].point.lat}
                that.form.lngAndLat = `${result.surroundingPois[0].point.lng},${result.surroundingPois[0].point.lat}`
              } else {
                that.form.address = result.address; //获取到当前定位的详细地址信息
                that.longitude=result.point.lng
                that.latitude=result.point.lat
                that.center = {lng: result.point.lng, lat: result.point.lat}
                that.form.lngAndLat = `${result.point.lng},${result.point.lat}`
              }
              // that.$set(that.form, 'address', result.address)
            });
          }
        }

      })
    },
    //信息窗口关闭
    infoWindowClose(){
      this.latitude=''
      this.longitude=''
      this.infoWindowShow=false
    },
    // 初始化，实例对象，默认获取地图的中心点
    handler ({ BMap, map }) {
      const myGeo = new BMap.Geocoder();
      // 选择一个经纬度作为中心点lng: 102.728433, lat: 25.021204
      this.point = new BMap.Point(98.581008, 24.442485); // 116.413384, 39.910925
      map.centerAndZoom(this.point, 17);
      this.BMap=BMap
      this.map=map
      const that = this
      if (!that.form.deptId) {
        myGeo.getLocation(this.point,function(result){
          console.log(result)
        });
      }
      // 纬度:39.910925,经度:116.413384
      // this.form.lngAndLat = '39.910925,116.413384'
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["serviceRef"].validate((valid) => {
        console.log(this.form)
        if (valid) {
          let item = this.form.lngAndLat.split(',')
          let position = ba_gd(parseFloat(item[1]), parseFloat(item[0])) // bdMapToTxMap
          console.log(position)
          const obj = {
            typeId: 3,
            lon: position.lng,
            lat: position.lat,
            orderNum: 1,
            serviceType: this.form.serviceType.join(','),
          }
          if (this.form.deptInfo && this.form.deptInfo.payBankCard) {
            this.form.deptInfo.payBankCard = this.form.deptInfo.payBankCard.replaceAll(' ', '')
          }
          console.log(Object.assign(this.form, obj))
          this.buttonLoading = true;
          if (this.form.deptId != undefined) {
            this.buttonLoading = false;
            updateDept(Object.assign(this.form, obj)).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$parent.getList();
            });
          } else {
            addDept(Object.assign(this.form, obj)).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.buttonLoading = false;
              this.$parent.getList();
            });
          }
        }
      });
    },
  }
}
</script>

<style scoped>
::v-deep.BMap_mask {
  height: 300px!important;
}

::v-deep .anchorBL {
  display: none !important;
}
</style>
